<?php
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2023 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------
namespace crmeb\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use Workerman\Worker;
use think\facade\Db;
use Workerman\Lib\Timer as Ttime;
class Timer extends Command
{
    /**
     * @var int
     */
    protected $timer;

    /**
     * @var int|float
     */
    protected $interval = 60;

    protected function configure()
    {
//        $o = new Output();
//        $o->writeln(Option::VALUE_NONE);
        // 指令配置
        $this->setName('timer')
            ->addArgument('status', Argument::REQUIRED, 'start/stop/reload/status/connections')
            ->addOption('d', null, Option::VALUE_NONE, 'daemon（守护进程）方式启动')//必传参数 php think timer start --d 以守护进程方式启动
            ->addOption('i', null, Option::VALUE_OPTIONAL, '多长时间执行一次,可以精确到0.001')//可选参数 接收上面i的值也就是intervl的值  php think timer start --i 0.1   =就是1秒，--i 1 = 1秒， --i 10 = 10秒
            ->setDescription('start/stop/restart 定时任务');
    }

    protected function init(Input $input, Output $output)
    {
        global $argv;

        if ($input->hasOption('i'))
            $this->interval = floatval($input->getOption('i'));

        $argv[1] = $input->getArgument('status') ?: 'start';//如果输入的命令是php think timer start 或者 php think timer status 那意义相等于 php think timer start  --d
        if ($input->hasOption('d')) {
            $argv[2] = '-d';
        } else {
            unset($argv[2]);
        }
    }

    protected function execute(Input $input, Output $output)
    {
        $this->init($input, $output);//初始化接受到的值
        Worker::$pidFile = app()->getRootPath().'runtime/timer.pid';
        $task = new Worker();
        date_default_timezone_set('PRC');
        $task->count = 1;
        $interval = $this->interval;
        $task->onWorkerStart = function () use ($task,$interval) {
            Ttime::add($interval, function()
            {
                event('CrontabListener');//执行event里的CrontabListener服务
            });
        };
        $task->runAll();
    }
}
